package com.wwwarehouse.financialcenter.fragment.moneywarehouse.payment;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.bean.PayBean;
import com.wwwarehouse.common.bean.PaymentParamBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.eventbus_event.PayResultEvent;
import com.wwwarehouse.common.tools.DeviceUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PayBaseUtil;
import com.wwwarehouse.common.tools.PayUtil;
import com.wwwarehouse.financialcenter.R;
import com.wwwarehouse.financialcenter.constant.FinancialConstant;
import com.wwwarehouse.financialcenter.customview.AutoClickButton;
import com.wwwarehouse.financialcenter.eventbus.Event;
import com.wwwarehouse.financialcenter.eventbus.EventHideTitle;
import com.wwwarehouse.financialcenter.fragment.base.TheParentFragment;
import com.wwwarehouse.financialcenter.utils.EventBusUtil;

import static com.tencent.mm.sdk.modelbase.BaseResp.ErrCode.ERR_OK;
import static com.wwwarehouse.financialcenter.constant.FinancialConstant.PATH_PAYMENT;


/**
 * @author Joseph on 2017/11/21.
 *         <p/>
 *         支付功能
 */
@Route(path = PATH_PAYMENT)
public class PaymentFragment extends TheParentFragment implements View.OnClickListener ,IWXAPIEventHandler,PayBaseUtil.AliPayListener {


    private TextView mPrice; //价格
    private TextView mPayee; //收款方
    private TextView mOrder; //订单
    private TextView mBillType; //费用类型（0=订购商品，1=取消订购，2=销售商品，3=劳务）
    private RelativeLayout mPayAlipay ;//支付宝
    private RelativeLayout mPayWechat ;//微信
    private RelativeLayout mPayUnionpay ;//银联
    private ImageView mImgAlipay ;
    private ImageView mImgWechat ;
    private ImageView mImgUnionpay ;
    private TextView mRead; //是否同意支付条例
    private TextView mWebRegulations; //跳转支付条例
    private AutoClickButton mConfirmBtn ;
    private boolean isRead  = true;
    private String platFormId = "1310";
    private PaymentParamBean paymentParamBean;
    private PayUtil payUtil;
    public static final int PAY_SUCCESS= 1; //成功
    public static final int PAY_WAIT = 2;  //等待
    public static final int PAY_FAIL = 3;  //失败
    private String billAmount;

    @Override
    protected int getContentId() {
        return R.layout.financial_center_payment;
    }

    @Override
    public void setTitle() {
        mActivity.setTitle(getString(R.string.financial_center_payment));
    }
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }
    @Override
    protected void init(View view) {
    mPrice = findView(view,R.id.price);
        mPayee = findView(view,R.id.payee);
        mOrder = findView(view,R.id.order);
        mPayAlipay = findView(view,R.id.rl_pay_alipay);
        mPayWechat = findView(view,R.id.rl_pay_wechat);
        mPayUnionpay = findView(view,R.id.rl_pay_unionpay);
        mImgAlipay = findView(view,R.id.img_pay_alipay);
        mImgWechat = findView(view,R.id.img_pay_wechat);
        mImgUnionpay = findView(view,R.id.img_pay_unionpay);
        mRead = findView(view,R.id.tv_read);
        mWebRegulations = findView(view,R.id.tv_web_regulations);
        mWebRegulations.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );
        mConfirmBtn = findView(view,R.id.confirm_btn);
        mBillType = findView(view,R.id.bill_type);
        mConfirmBtn.setEnabled(true);
        mConfirmBtn.setOnClickListener(this);
        mRead.setOnClickListener(this);
        mWebRegulations.setOnClickListener(this);
        mPayAlipay.setOnClickListener(this);
        mPayWechat.setOnClickListener(this);
        mPayUnionpay.setOnClickListener(this);
    }

    @Override
    protected void loadDatas() {
        Bundle bundle = getArguments();
        if (bundle!=null){
            paymentParamBean = (PaymentParamBean) bundle.getSerializable("payment_param");
            if (paymentParamBean!=null){
                billAmount = paymentParamBean.getBillAmount();
                if (!TextUtils.isEmpty(billAmount)){
                    billAmount = billAmount.replace("+", "");
                    mPrice.setText(billAmount);
                }
                mPayee.setText("收款方:"+paymentParamBean.getOtherSideName());
                mOrder.setText("订单"+paymentParamBean.getBillTradeNo());
                mBillType.setText(paymentParamBean.getBillType());
            }
        }
        payUtil = new PayUtil(mActivity);
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {

    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.confirm_btn) {
            PayBean payBean = new PayBean();
            switch (platFormId){
                case "1310": //支付宝
                    payBean.setClientIp(DeviceUtils.getIPAddress(mActivity));
                    payBean.setOpenId("11");
                    payBean.setP2c(false);
                    payBean.setPlatFormId(platFormId);
//                    payBean.setRegAppType("QY");
                    payBean.setTradeNo(paymentParamBean.getBillTradeNo());
                    payUtil.aliPay(payBean,this);
                    break;
                case "1320"://微信
                    payBean.setClientIp(DeviceUtils.getIPAddress(mActivity));
                    payBean.setOpenId(BaseApplication.getApplicationInstance().getAPP_ID());
                    payBean.setP2c(false);
                    payBean.setPlatFormId("1320");
                    payBean.setRegAppType("wx");
                    payBean.setTradeNo(paymentParamBean.getBillTradeNo());
                    payUtil.WXpay(payBean);
                    break;

                case "1330": //银联
                    payBean = new PayBean();
                    payBean.setClientIp(DeviceUtils.getIPAddress(mActivity));
                    payBean.setOpenId("11");
                    payBean.setP2c(false);
                    payBean.setPlatFormId("1330");
                    payBean.setRegAppType("YL");
                    payBean.setTradeNo(paymentParamBean.getBillTradeNo());
                    payUtil.unionPay(payBean);
                    break;
            }

        } else if (i == R.id.tv_read) {
            isRead = !isRead;
            if (isRead){
                mConfirmBtn.setEnabled(true);
                Drawable rightDrawable = getResources().getDrawable(R.drawable.financial_center_select);
                rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
                mRead.setCompoundDrawables(rightDrawable, null, null, null);
            }else {
                mConfirmBtn.setEnabled(false);
                Drawable rightDrawable = getResources().getDrawable(R.drawable.financial_center_not_selected);
                rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
                mRead.setCompoundDrawables(rightDrawable, null, null, null);
            }
        } else if (i == R.id.tv_web_regulations) {
            Bundle bundle = new Bundle();
            bundle.putString("url", FinancialConstant.URL_PAY_PROTOCOL);
            bundle.putString("title", getString(R.string.financial_center_ordinance));
            PaymentWebViewFragment commonBridgeWebViewFragment = new PaymentWebViewFragment();
            commonBridgeWebViewFragment.setArguments(bundle);
            pushFragment(commonBridgeWebViewFragment);

        } else if (i == R.id.rl_pay_alipay) {
            platFormId = "1310";
           mImgAlipay.setVisibility(View.VISIBLE); ;
           mImgWechat.setVisibility(View.GONE) ;
            mImgUnionpay.setVisibility(View.GONE) ;
        } else if (i == R.id.rl_pay_wechat) {
            platFormId = "1320";
            mImgAlipay.setVisibility(View.GONE); ;
            mImgWechat.setVisibility(View.VISIBLE) ;
            mImgUnionpay.setVisibility(View.GONE) ;
        } else if (i == R.id.rl_pay_unionpay) {
            platFormId = "1330";
            mImgAlipay.setVisibility(View.GONE); ;
            mImgWechat.setVisibility(View.GONE) ;
            mImgUnionpay.setVisibility(View.VISIBLE) ;
        }
    }
    //银联回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
                //处理银联手机支付控件返回的支付结果
        if (data == null) {
            return;
        }

        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {

            // 如果想对结果数据验签，可使用下面这段代码，但建议不验签，直接去商户后台查询交易结果
            // result_data结构见c）result_data参数说明

//            if (data.hasExtra("result_data")) {
//                String result = data.getExtras().getString("result_data");
//                try {
//                    JSONObject resultJson = new JSONObject(result);
//                    String sign = resultJson.getString("sign");
//                    String dataOrg = resultJson.getString("data");
//                    // 此处的verify建议送去商户后台做验签
//                    // 如要放在手机端验，则代码必须支持更新证书
//                    boolean ret = verify(dataOrg, sign, mMode);
//                    if (ret) {
//                        // 验签成功，显示支付结果
//                        msg = "支付成功！";
//                    } else {
//                        // 验签失败
//                        msg = "支付失败！";
//                    }
//                } catch (JSONException e) {
//                }
//            }
            // 结果result_data为成功时，去商户后台查询一下再展示成功
            msg = "支付成功！";
            goStatusPage(PaymentFragment.PAY_SUCCESS, billAmount);
        } else if (str.equalsIgnoreCase("fail")) {
            goStatusPage(PaymentFragment.PAY_FAIL, billAmount);
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "取消支付";
            toastAtTop(msg);
        }

    }
    @Override
    public void onReq(BaseReq baseReq) {

    }
    //微信回调
    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == ERR_OK) {
                goStatusPage(PaymentFragment.PAY_SUCCESS, billAmount);
            } else if (resp.errCode == -1) {
                goStatusPage(PaymentFragment.PAY_FAIL, billAmount);
            } else if (resp.errCode == -2) {
                toast("取消支付");
            }

        }
    }
    //支付宝回调
    @Override
    public void success() {
        LogUtils.showInfoLog("支付宝-success");
//        goStatusPage(PaymentFragment.PAY_SUCCESS, billAmount);
    }

    @Override
    public void failed() {
        LogUtils.showInfoLog("支付宝-failed");
//        goStatusPage(PaymentFragment.PAY_FAIL, billAmount);
    }

    @Override
    public void paying() {
        LogUtils.showInfoLog("支付宝-paying");
//        goStatusPage(PaymentFragment.PAY_WAIT, billAmount);
    }
    private void goStatusPage(int paySuccess, String billAmount) {
        PaymentStatusFragment fragment = new PaymentStatusFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("status", paySuccess);
        bundle.putString("billAmount", billAmount);
        fragment.setArguments(bundle);
        pushFragment(fragment);
    }
    public void onEventMainThread(PayResultEvent event) {
        if (event != null) {
            String msg = event.getMsg();
            switch (msg){
                case "success":
                    LogUtils.showInfoLog("onEventMainThread-paying");
                    EventBusUtil.sendEvent(new Event(EventHideTitle.CODE.B,new EventHideTitle()));
                    popFragment();
                    goStatusPage(PaymentFragment.PAY_SUCCESS, billAmount);

                    break;
                case "failure":
                    LogUtils.showInfoLog("onEventMainThread-failure");
                    goStatusPage(PaymentFragment.PAY_FAIL, billAmount);

                    break;
                case "cancel":
                    LogUtils.showInfoLog("onEventMainThread-cancel");
                    toastAtTop("支付已被您取消");

                    break;
            }

        }
    }
}
